import axios from "axios";
import store from "../store";
import token from "../token";

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8888/blog/',
    timeout: 10000
})

//请求拦截器配置
axiosInstance.interceptors.request.use(config => {
    //每次请求都携带token（保证localStorage里面的token是最新的）
    if(store.state.token) {
        config.headers['token'] = store.state.token
    }
    return config;
}, error => {
    return Promise.reject(error);
});

//响应拦截器配置
axiosInstance.interceptors.response.use(response => {
    //每次请求完成后，保证token都是最新的（token续约）
    let token = response.headers['token']
    if(token) {
        store.commit('setToken',token)
    }

    //============对错误响应进行统一处理==============
    //获取后端返回的对象
    const res = response.data;
    if(response.status == 200) {
        //数据正常响应
        if(res.status == 200) {
            return res;
        } else {
            //将错误信息响应给具体调用的页面
            return Promise.reject(res.msg);
        }
    }
}, error => {
    return Promise.reject(error);
});

export default axiosInstance